package servlet.song;

import com.alibaba.fastjson.JSON;
import pojo.Result;
import pojo.SongRequest;
import service.SongRequestService;
import service.impl.SongRequestServiceImpl;
import utils.JsonUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.stream.Collectors;

@WebServlet("/song/sendSongServlet")
public class SendSongServlet extends HttpServlet {
    SongRequestService songRequestService = new SongRequestServiceImpl();
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String data = req.getReader().lines().collect(Collectors.joining(System.lineSeparator()));
        SongRequest songRequest = JsonUtils.jsonToPojo(data, SongRequest.class);
        Result result = new Result();
        // 设置响应乱码
        resp.setCharacterEncoding("UTF-8");
        if (songRequest == null) {
            result = Result.error("请求参数有误");
            return;
        }
        // 给别人发音乐，实际是就是给音乐盒子中插入数据
        boolean flag = songRequestService.insertSongRequest(songRequest);
        if (flag) {
            result = Result.success();
        } else {
            result = Result.error("发送请求失败");
        }
        resp.getWriter().write(JSON.toJSONString(result));
        resp.getWriter().close();
        resp.getWriter().flush();
    }
}
